import 'package:chat_app_project/constants.dart';
import 'package:chat_app_project/models/ChatMessage.dart';
import 'package:chat_app_project/screens/messages/components/message.dart';
import 'package:flutter/material.dart';
import 'package:wukongimfluttersdk/entity/channel.dart';
import 'package:wukongimfluttersdk/wkim.dart';

import '../../../models/msg.dart';
import 'chat_input_fields.dart';

class Body extends StatefulWidget {
  WKChannel currentChannel;

  Body({super.key, required this.currentChannel});

  @override
  State<Body> createState() => _BodyState();
}

class _BodyState extends State<Body> {
    late String channelID;
    late int channelType;

    @override
    void initState() {
      super.initState();
      channelID = widget.currentChannel.channelID;
      channelType = widget.currentChannel.channelType;

      getMsgList();
      initListener();
    }
  //消息列表
  List<UIMsg> msgList = [];
  final ScrollController _scrollController = ScrollController();

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Expanded(
          child: Container(
            margin: const EdgeInsets.only(bottom: kDefaultPadding / 2),
            child: Padding(
              padding:
                  const EdgeInsets.symmetric(horizontal: kDefaultPadding / 2),
              child: GestureDetector(
                onTap: (){
                  debugPrint("点击了消息列表 ======================");
                  var currentState = chatInputFieldKey.currentState;
                  currentState?.textUnfocus();
                },
                child: ListView.builder(
                  //数据反转  滚动到底部就是list上部position为0 list追加插入到头部
                  reverse: true,
                  // shrinkWrap: true,
                  controller: _scrollController,
                  itemCount: msgList.length,
                  itemBuilder: (context, index) =>
                      Message(message: msgList[index]),
                ),
              ),
            ),
          ),
        ),
        ChatInputField(
          key: chatInputFieldKey,
            currentChannel: widget.currentChannel,
            scrollToBottom: () {
              debugPrint("文本框点击时滚动到底部 ======================");
              //文本框点击时滚动到底部
              scrollToBottom();
            })
      ],
    );
  }


  //滚动到底部
  scrollToBottom() {
    _scrollToBottom(false);
  }
  //滚动到底部
  _scrollToBottom(bool twoScroll) {
    Future.delayed(const Duration(milliseconds: 500), () {
      _scrollController
          // .animateTo(_scrollController.position.maxScrollExtent,
          .animateTo(0,
              duration: const Duration(milliseconds: 300),
              curve: Curves.easeOut)
          .whenComplete(() {
        debugPrint("滚动到底部完成");
        if(twoScroll){
          Future.delayed(const Duration(milliseconds: 100), () {
            _scrollController
                .animateTo(0,
                duration: const Duration(milliseconds: 200),
                curve: Curves.easeOut)
                .whenComplete(() {
              debugPrint("二次滚动到底部完成");
            });
          });
        }
      });
    });
  }

  initListener() {
    WKIM.shared.messageManager.addOnMsgInsertedListener((wkMsg) async {
      debugPrint(
          " addOnMsgInsertedListener ====== wkMsg.channelID ${wkMsg.channelID} channelID $channelID");
      var channel = await WKIM.shared.channelManager
          .getChannel(wkMsg.channelID, wkMsg.channelType);
      wkMsg.setChannelInfo(channel);
      WKIM.shared.channelManager
          .getChannel(wkMsg.fromUID, wkMsg.channelType)
          .then((value) {
        //触发更新
        if (value == null) {
          WKIM.shared.channelManager
              .fetchChannelInfo(wkMsg.fromUID, wkMsg.channelType);
        } else {
          wkMsg.setFrom(value);
        }
      });
      setState(() {
        msgList.insert(0,UIMsg(wkMsg));
      });
      scrollToBottom();
    });
    WKIM.shared.messageManager.addOnNewMsgListener('chat', (msgs) async {
      debugPrint(" addOnNewMsgListener ====== ");
      for (var i = 0; i < msgs.length; i++) {
        //过滤非本频道数据
        var msg = msgs[i];
        if (msg.channelID != channelID) {
          return;
        }
        var channel = await WKIM.shared.channelManager
            .getChannel(msg.channelID, msg.channelType);
        msg.setChannelInfo(channel);
        var fromChannel = await WKIM.shared.channelManager
            .getChannel(msg.fromUID, msg.channelType);
        msg.setFrom(fromChannel!);
        msgList.insert(0,UIMsg(msg));
      }
      setState(() {});
      //滚动到底部
      scrollToBottom();
    });
    WKIM.shared.messageManager.addOnRefreshMsgListener('chat', (wkMsg) {
      debugPrint(" addOnRefreshMsgListener ====== ");
      for (var i = 0; i < msgList.length; i++) {
        if (msgList[i].wkMsg.clientMsgNO == wkMsg.clientMsgNO) {
          msgList[i].wkMsg.messageID = wkMsg.messageID;
          msgList[i].wkMsg.messageSeq = wkMsg.messageSeq;
          msgList[i].wkMsg.status = wkMsg.status;
          break;
        }
      }
      setState(() {});
      scrollToBottom();
    });

    //  监听channel刷新事件
    //   WKIM.shared.channelManager.addOnRefreshListener('chat', (wkChannel) {
    //     // 刷新对应channel 信息
    //     debugPrint("监听channel刷新事件  ================ $wkChannel");
    //     for (var element in msgList) {
    //       var wkMsg = element.wkMsg;
    //       if (wkMsg.getFrom() == null) {
    //         if (wkChannel.channelID == wkMsg.fromUID) {
    //           wkMsg.setFrom(wkChannel);
    //         }
    //         if (wkChannel.channelID == wkMsg.channelID) {
    //           wkMsg.setChannelInfo(wkChannel);
    //         }
    //       }
    //     }
    //     setState(() {});
    //   });
  }

  getMsgList() async {
    int maxSeq = await WKIM.shared.messageManager
        .getMaxMessageSeq(channelID, channelType);
    int orderSeq = await WKIM.shared.messageManager
        .getMessageOrderSeq(maxSeq, channelID, channelType);
    debugPrint('orderSeq $orderSeq');
    bool pull_to_down = true;
    WKIM.shared.messageManager.getOrSyncHistoryMessages(
        channelID, channelType, orderSeq, true, pull_to_down ? 0 : 1, 50, 0,
        (list) {
      for (int i = 0; i < list.length; i++) {
        debugPrint('messageSeq ${list[i].messageSeq}');
        msgList.insert(0,UIMsg(list[i]));
      }
      // msgList = msgList.reversed.toList();
      setState(() {});
      //滚动到底部
      // _scrollToBottom(true);
    }, () {
      debugPrint('消息同步中');
    });
  }

  @override
  void dispose() {
    super.dispose();
    WKIM.shared.messageManager.removeNewMsgListener('chat');
    WKIM.shared.messageManager.removeOnRefreshMsgListener('chat');
    WKIM.shared.channelManager.removeOnRefreshListener('chat');
    //消除外层红点
    WKIM.shared.conversationManager.updateRedDot(channelID, channelType, 0);
  }
}
